package com.gome.axwl.aoc.facade.impl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.anxl.sso.client.api.Account;
import com.anxl.sso.client.api.AccountInfo;
import com.github.pagehelper.PageInfo;
import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.axwl.aoc.entity.dto.FileUploadRecordDto;
import com.gome.axwl.aoc.entity.dto.PageResultDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApplyInfoDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApplyInfoForListDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApplyInfoForListParamDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApprovalParamDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsServerInfoDto;
import com.gome.axwl.aoc.entity.enums.BusinessEnum;
import com.gome.axwl.aoc.entity.exception.ZQException;
import com.gome.axwl.aoc.entity.po.AmAuditSettingPo;
import com.gome.axwl.aoc.entity.po.ApprovalRecordPo;
import com.gome.axwl.aoc.entity.po.BuildEmptyContractRequest;
import com.gome.axwl.aoc.entity.po.CsApplyInfoForListPo;
import com.gome.axwl.aoc.entity.po.CsApplyInfoParmPo;
import com.gome.axwl.aoc.entity.po.CsApplyInfoPo;
import com.gome.axwl.aoc.entity.po.CsBasicInfoPo;
import com.gome.axwl.aoc.entity.po.CsLicenseInfoPo;
import com.gome.axwl.aoc.entity.po.FileUploadRecordPo;
import com.gome.axwl.aoc.facade.CarrierSettleFacade;
import com.gome.axwl.aoc.facade.ContractFacade;
import com.gome.axwl.aoc.facade.SmsSendFacade;
import com.gome.axwl.aoc.service.ApprovalRecordService;
import com.gome.axwl.aoc.service.AuditSettingService;
import com.gome.axwl.aoc.service.CsApplyinfoService;
import com.gome.axwl.aoc.service.CsBasicInfoService;
import com.gome.axwl.aoc.service.CsLicenseInfoService;
import com.gome.axwl.aoc.service.FileUploadRecordService;
import com.gome.axwl.aoc.service.feign.MasterDataFeignClient;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import com.gome.datasource.shard.annotation.ReadDatasource;


/**
 * CarrierSettleFacadeImpl 服务商入驻运营平台门面实现
 * @author chenjunjie
 * @since 2018-07-17
 */
@Service("carrierSettleFacade")
public class CarrierSettleFacadeImpl implements CarrierSettleFacade {


    private static final Logger LOGGER= LoggerFactory.getLogger(CarrierSettleFacadeImpl.class);

    @Autowired
    private CsApplyinfoService csApplyinfoService;
    @Autowired
    private CsLicenseInfoService csLicenseInfoService;
    @Autowired
    private CsBasicInfoService csBasicInfoService;
    @Autowired
    private FileUploadRecordService fileUploadRecordService;
    @Autowired
    private ApprovalRecordService approvalRecordService;
    @Autowired
    private AuditSettingService auditSettingService;
    @Autowired
    private ContractFacade contractFacade;
    @Autowired
    private MasterDataFeignClient masterDataFeignClient;
    @Autowired
    private SmsSendFacade smsSendFacade;

    @Value("${carrierSettle.companyName}")
    private String companyName;
    @Value("${carrierSettle.messageForBusiness}")
    private String messageForBusiness;
    @Value("${carrierSettle.messageForCarrier}")
    private String messageForCarrier;

    @Override
    public ResultData<CsApplyInfoDto> getApprovalDetailById(Integer applyInfoId) {
        ResultData<CsApplyInfoDto> resultData = new ResultData<>();
        try {
            CsApplyInfoPo applyInfoPo = csApplyinfoService.queryWithAssociateById(applyInfoId);
            CsApplyInfoDto csApplyInfoDto = BeanJsonUtil.beanConvert(applyInfoPo, CsApplyInfoDto.class);
            //获取附件url
            List<FileUploadRecordPo> attachmentUrl = fileUploadRecordService.queryByFileScenesAndSencesId(BusinessEnum.CARRIER_SETTLE_FILE_TYPE_ATTACHMENT.getItemCode(), applyInfoId);
            csApplyInfoDto.setAttchamentList(BeanJsonUtil.listConvert(attachmentUrl,FileUploadRecordDto.class));
            //获取审核拒绝原因
            ApprovalRecordPo approvalRecordPo=new ApprovalRecordPo();
            approvalRecordPo.setApprovalApplyId(applyInfoId);
            approvalRecordPo.setApprovalType(BusinessEnum.APPROVAL_TYPE_CS_OPERATION.getItemCode());
            approvalRecordPo.setApprovalResult(BusinessEnum.APPROVAL_STATUS_PENDING.getItemCode());
            List<ApprovalRecordPo> approvalRecordPos = approvalRecordService.queryApprovalHistory(approvalRecordPo);
            if (approvalRecordPos!=null && approvalRecordPos.size()>0){
                csApplyInfoDto.setApprovalResultContent(approvalRecordPos==null?null:approvalRecordPos.get(0)==null?null:approvalRecordPos.get(0).getApprovalResultContent());
            }
            if (StringUtils.isNotBlank(csApplyInfoDto.getCmContractNo())){
                List<String> detail = contractFacade.getDetail(csApplyInfoDto.getCmContractNo());
                csApplyInfoDto.setAtractImgThumbList(detail);
            }
            //获取服务类型
            List<String> serverCodeList=new ArrayList<>();
            if (StringUtils.isNotBlank(csApplyInfoDto.getServerType())){
                serverCodeList=Arrays.asList(csApplyInfoDto.getServerType().split(","));
            }
            if (serverCodeList!=null && serverCodeList.size()>0){
                List<CsServerInfoDto>serverNameList=new ArrayList<>();
                for (String serverCode: serverCodeList){
                    CsServerInfoDto csServerInfoDto=new CsServerInfoDto();
                    csServerInfoDto.setServerCode(serverCode);
                    csServerInfoDto.setServerName(BusinessEnum.queryNameByItemCodeAndType(serverCode,"cs_server_type"));
                    serverNameList.add(csServerInfoDto);
                }
                csApplyInfoDto.setCsServerInfoList(serverNameList);
            }
            //入驻类型中文编码
            csApplyInfoDto.setApprovalStatusDesc(BusinessEnum.queryNameByItemCodeAndType(csApplyInfoDto.getApprovalStatus(),"cs_approval_status"));
            //邀请人
            List<String> inviteNos=new ArrayList<>();
            inviteNos.add(applyInfoPo.getSettleInviteNo());
            ResultData<List<AccountInfo>> accountListByInviteCodes = masterDataFeignClient.getAccountListByInviteCodes(inviteNos);
            if (accountListByInviteCodes!=null && accountListByInviteCodes.getData()!=null && accountListByInviteCodes.getData().size()>0){
                AccountInfo accountInfo=accountListByInviteCodes.getData().get(0);
                csApplyInfoDto.setInviter(accountInfo.getName()+"/"+accountInfo.getAccountNo()+"/"+accountInfo.getInvitationCode());
            }
            resultData.setData(csApplyInfoDto);
            return resultData;
        } catch (Exception e) {
            LOGGER.error("根据申请号查询申请详情--error:{}", ExceptionUtils.getFullStackTrace(e));
            resultData.setCode(ErrorCode.QUERY_FAILOR);
            resultData.setMessage(ErrorCode.QUERY_FAILOR_MSG);
            return resultData;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData<Integer> createSettleApplyInfo(CsApplyInfoDto csApplyInfoDto) {

        CsApplyInfoPo csApplyInfoPo=BeanJsonUtil.beanConvert(csApplyInfoDto,CsApplyInfoPo.class);
        List<CsServerInfoDto> csServerCodeList=csApplyInfoDto.getCsServerInfoList();
        if (csServerCodeList!=null && csServerCodeList.size()>0){
            StringBuffer csServerCode=new StringBuffer();
            for (CsServerInfoDto csServerCodeStr:csServerCodeList){
                csServerCode.append(csServerCodeStr.getServerCode()).append(",");
            }
            csApplyInfoPo.setServerType(csServerCode.substring(0,csServerCode.length()-1));
        }
        CsBasicInfoPo csBasicInfoPo=csApplyInfoPo.getCsBasicInfo();
        CsLicenseInfoPo csLicenseInfoPo=csApplyInfoPo.getCsLicenseInfo();

        try {
            //1：保存从表记录 csLicenseInfoPo
            if (!Objects.isNull(csLicenseInfoPo)){
                csLicenseInfoService.insert(csLicenseInfoPo);
            }
            //2：保存从表记录 csBasicInfopo
            if (!Objects.isNull(csBasicInfoPo)){
                //2.1:保存csBasicInfo
                csBasicInfoService.insert(csBasicInfoPo);
            }
            //3：保存主表 csApplyInfo
            csApplyInfoPo.setDeleteStatus((byte)1);
            csApplyInfoPo.setCreateDate(new Date());
            csApplyInfoPo.setCsBasicInfoId(csBasicInfoPo.getId());
            csApplyInfoPo.setCsLicenseInfoId(csLicenseInfoPo.getId());
            csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS__DRA.getItemCode());
            csApplyinfoService.insert(csApplyInfoPo);
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,csApplyInfoPo.getId());
        }catch (DuplicateKeyException e1){
            LOGGER.error("新增入驻申请单出现异常:{}",ExceptionUtils.getFullStackTrace(e1));
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData<>(ErrorCode.ADD_FAILOR,"已有入驻申请记录，请勿重复提交");
        }catch (Exception e2) {
            LOGGER.error("新增入驻申请单出现异常:{}",ExceptionUtils.getFullStackTrace(e2));
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData<>(ErrorCode.ADD_FAILOR,ErrorCode.ADD_FAILOR_MSG);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData<Integer> commitSettleApplyInfo(CsApplyInfoDto csApplyInfoDto) {

        if (csApplyInfoDto.getId()==null){
            LOGGER.error("保存入驻申请单失败，未查询到指定记录,param{}",BeanJsonUtil.obj2String(csApplyInfoDto));
            return new ResultData<>(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }
        try {
            //只修改接受的字段项
            //对于图片等文件的修改关联 直接覆盖即可
            CsApplyInfoPo csApplyInfoPoForUpdate=BeanJsonUtil.beanConvert(csApplyInfoDto,CsApplyInfoPo.class);
            CsApplyInfoPo csApplyInfoPo1=csApplyinfoService.queryById(csApplyInfoDto.getId());
            if (!Objects.isNull(csApplyInfoDto.getCsBasicInfo())){
                if (csApplyInfoDto.getCsBasicInfo().getId()==null){
                    csBasicInfoService.insert(BeanJsonUtil.beanConvert(csApplyInfoDto.getCsBasicInfo(),CsBasicInfoPo.class));
                    csApplyInfoPoForUpdate.setCsBasicInfoId(csApplyInfoDto.getCsBasicInfo().getId());
                }else {
                    csBasicInfoService.update(BeanJsonUtil.beanConvert(csApplyInfoDto.getCsBasicInfo(),CsBasicInfoPo.class));
                }
            }
            if (!Objects.isNull(csApplyInfoDto.getCsLicenseInfo())){
                if (null==csApplyInfoDto.getCsLicenseInfo().getId()){
                    csLicenseInfoService.insert(BeanJsonUtil.beanConvert(csApplyInfoDto.getCsLicenseInfo(),CsLicenseInfoPo.class));
                    csApplyInfoPoForUpdate.setCsLicenseInfoId(csApplyInfoDto.getCsLicenseInfo().getId());
                }
                csLicenseInfoService.update(BeanJsonUtil.beanConvert(csApplyInfoDto.getCsLicenseInfo(),CsLicenseInfoPo.class));
            }
            List<String> csServerCodeList=new ArrayList<>();
            if (csServerCodeList!=null && csServerCodeList.size()>0){
                StringBuffer csServerCode=new StringBuffer();
                for (String csServerCodeStr:csServerCodeList){
                    csServerCode.append(csServerCodeStr).append(",");
                }
                csApplyInfoPoForUpdate.setServerType(csServerCode.substring(0,csServerCode.length()-1));
            }
            csApplyInfoPoForUpdate.setModifyDate(new Date());
            //有必填项未填，只修改 不启动审批
            if (StringUtils.isBlank(csApplyInfoDto.getCarrrierSettleName())){
                csApplyinfoService.update(csApplyInfoPoForUpdate);
                return new ResultData<>(ErrorCode.FAILOR,"请补充必填项后再提交");
            }
            AccountInfo accountInfo = this.queryAccountInfoByAccountNoOrInviteNo(null, csApplyInfoPo1.getSettleInviteNo());
            if (accountInfo==null){
                throw new RuntimeException("操作失败，邀请码无对应用户信息");
            }
            Boolean userHasAuditPrivilege = auditSettingService.isUserHasAuditPrivilege(accountInfo.getAccountNo());
            csApplyInfoPoForUpdate.setApprovalType(userHasAuditPrivilege?BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_SPECIAL.getItemCode():BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_DEFAULT.getItemCode());

            csApplyInfoPoForUpdate.setSettleStartDate(new Date());
            csApplyInfoPoForUpdate.setDeleteStatus((byte)1);
            csApplyInfoPoForUpdate.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_OP.getItemCode());
            csApplyinfoService.update(csApplyInfoPoForUpdate);
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,csApplyInfoPoForUpdate.getId());
        } catch (Exception e) {
            LOGGER.error("修改入驻申请单出现异常:{}",ExceptionUtils.getFullStackTrace(e));
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData<>(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData<Void> approvalApplyInfo(CsApprovalParamDto csApprovalParamDto) {
        try {
            //0：查询入驻申请单基础信息和审批流程信息
            CsApplyInfoPo csApplyInfoPo = csApplyinfoService.queryById(csApprovalParamDto.getApplyInfoId());
            AccountInfo approvalAccountInfo = this.queryAccountInfoByAccountNoOrInviteNo(csApprovalParamDto.getApprovalUserNo(), null);
            if (null==approvalAccountInfo){
                return new ResultData<>(ErrorCode.FAILOR,"获取当前用户信息失败");
            }
            //2：判断审核人是否有当前单子的审核权限
            String approvalType=csApplyInfoPo.getApprovalType();
            String approvalAuthority = this.checkApprovalAuthority(csApprovalParamDto.getApprovalUserNo());
            if (StringUtils.isBlank(approvalAuthority)){
                LOGGER.error("审批失败，无审批权限,csApplyInfo{},csApprovalUserNo{}",BeanJsonUtil.obj2String(csApplyInfoPo),csApprovalParamDto.getApprovalUserNo());
                return new ResultData<>(ErrorCode.FAILOR,"无审核权限");
            }
            if (StringUtils.equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_DEFAULT.getItemCode(),approvalType)){
                if (!StringUtils.equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_USER_TYPE_FINANCI.getItemCode(),approvalAuthority)
                        &&!StringUtils.equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_USER_TYPE_BUSINESS.getItemCode(),approvalAuthority)){
                    //默认运营审核单，判断当前登录人是不是默认审核人
                    LOGGER.error("审批失败，无审批权限,csApplyInfo{},csApprovalUserNo{}",BeanJsonUtil.obj2String(csApplyInfoPo),csApprovalParamDto.getApprovalUserNo());
                    return new ResultData<>(ErrorCode.FAILOR,"无审核权限");
                }
            }else if (StringUtils.equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_SPECIAL.getItemCode(),approvalType)){
                if (!StringUtils.equals(csApplyInfoPo.getSettleInviteNo(),approvalAccountInfo.getInvitationCode())){
                    LOGGER.error("审批失败，无审批权限,csApplyInfo{},csApprovalUserNo{}",BeanJsonUtil.obj2String(csApplyInfoPo),csApprovalParamDto.getApprovalUserNo());
                    return new ResultData<>(ErrorCode.FAILOR,"无审核权限");
                }
            } else if (StringUtils.equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_TRANSFER.getItemCode(),approvalType)) {
                //运营审核转移单 转移人必须是当前审批人
                if (!StringUtils.equals(csApplyInfoPo.getLastestTransferUserNo(),csApprovalParamDto.getApprovalUserNo())){
                    LOGGER.error("审批失败，无审批权限,csApplyInfo{},csApprovalUserNo{}",BeanJsonUtil.obj2String(csApplyInfoPo),csApprovalParamDto.getApprovalUserNo());
                    return new ResultData<>(ErrorCode.FAILOR,"无审核权限");
                }
            }

            //3:根据单子的状态判断执行的是什么审批
            if (csApplyInfoPo.getApprovalStatus().equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_OP.getItemCode())
                    ||csApplyInfoPo.getApprovalStatus().equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_FFA.getItemCode())){
                //运营审核（需要更新附件信息表的关联）
                if (csApprovalParamDto.getApprovalResult()!=1){
                    //拒绝
                    csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_OF.getItemCode());
                }else {
                    //运营审核通过
                    csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_FP.getItemCode());
                    csApplyInfoPo.setCautionMoney(csApprovalParamDto.getCautionMoney());

                }
                //附件处理
                //删除原本的附件记录
                fileUploadRecordService.batchDeleteByScenesAndSencesId(BusinessEnum.CARRIER_SETTLE_FILE_TYPE_ATTACHMENT.getItemCode(),csApplyInfoPo.getId());
                List<FileUploadRecordPo> fileUploadRecordPos = BeanJsonUtil.listConvert(csApprovalParamDto.getAttachmentList(), FileUploadRecordPo.class);
                if (fileUploadRecordPos!=null && fileUploadRecordPos.size()>0){
                    for (FileUploadRecordPo fileUploadRecordPo:fileUploadRecordPos){
                        fileUploadRecordPo.setScenesId(csApplyInfoPo.getId());
                        fileUploadRecordPo.setFileScenes(BusinessEnum.CARRIER_SETTLE_FILE_TYPE_ATTACHMENT.getItemCode());
                        fileUploadRecordPo.setUploadTime(new Date());
                        fileUploadRecordPo.setDeletedStatus((byte)1);
                    }
                    fileUploadRecordService.batchInsert(fileUploadRecordPos);
                }
                csApplyInfoPo.setApprovalUserNoBusiness(csApprovalParamDto.getApprovalUserNo());
            }else if (csApplyInfoPo.getApprovalStatus().equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_FP.getItemCode())){
                //财务审核
                if (csApprovalParamDto.getApprovalResult()==-1){
                    //资质未通过:让服务商修改申请单
                    csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_FFQ.getItemCode());
                }else if (csApprovalParamDto.getApprovalResult()==0){
                    csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_FFA.getItemCode());
                }else{
                    //通过
                    csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_SP.getItemCode());
                    csApplyInfoPo.setCmContractTemplateNo(csApprovalParamDto.getCmContractTemplateNo());
                    //送签
                    String contractNo = this.sendSignInBusnies(csApplyInfoPo, csApprovalParamDto.getCmContractName(), approvalAccountInfo);
                    csApplyInfoPo.setCmContractNo(contractNo);
                }
                csApplyInfoPo.setApprovalUserNoFinance(csApprovalParamDto.getApprovalUserNo());
            }else if (csApplyInfoPo.getApprovalStatus().equals(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_SPED.getItemCode())){
                //财务确认
                if (csApprovalParamDto.getApprovalResult()!=1){
                    //拒绝，服务商重新签署合同,然后财务再审核
                    csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_SP.getItemCode());
                }else {
                    this.sendSignInFinance(csApplyInfoPo.getId(),csApprovalParamDto.getApprovalResult(),approvalAccountInfo.getName(),csApprovalParamDto.getApprovalResultContent());
                    csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_SS.getItemCode());
                }
                csApplyInfoPo.setApprovalUserNoFinance(csApprovalParamDto.getApprovalUserNo());
            }else {
                //不满足审批状态
                return new ResultData<>(ErrorCode.FAILOR,"入驻申请单状态不符合审批要求,审批失败");
            }
            //新增审批记录
            ApprovalRecordPo approvalRecordPo=new ApprovalRecordPo();
            approvalRecordPo.setApprovalApplyId(csApplyInfoPo.getId());
            approvalRecordPo.setApprovalType(BusinessEnum.APPROVAL_TYPE_CS_OPERATION.getItemCode());
            approvalRecordPo.setApprovalTime(new Date());
            approvalRecordPo.setApprovalResultContent(csApprovalParamDto.getApprovalResultContent());
            approvalRecordPo.setApprovalResult(csApprovalParamDto.getApprovalResult()==1?"1":"0");
            approvalRecordPo.setApprovaUserName(approvalAccountInfo.getName());
            approvalRecordPo.setApprovalUserNo(csApprovalParamDto.getApprovalUserNo());
            approvalRecordService.insert(approvalRecordPo);
            //更新申请表相关信息
            csApplyinfoService.update(csApplyInfoPo);
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        } catch (Exception e) {
            LOGGER.error("申请入驻申请单出现异常:{}",ExceptionUtils.getFullStackTrace(e));
           //事务回滚m
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData<>(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }
    }

    @Override
    @ReadDatasource
    public ResultData<PageResultDto<CsApplyInfoForListDto>> queryCsApplyInfoList(CsApplyInfoForListParamDto csApplyInfoForListParamDto) {
        try {
            CsApplyInfoParmPo csApplyInfoParmPo=new CsApplyInfoParmPo();
            //判断当前用户具备什么类型的审批权限
            String approvalAuthority=this.checkApprovalAuthority(csApplyInfoForListParamDto.getApprovalUserNo());
            csApplyInfoParmPo.setApprovalUserType(approvalAuthority);
            if (StringUtils.isNotBlank(csApplyInfoForListParamDto.getServerTypeList())){
                List<String> serverTypeList=Arrays.asList(csApplyInfoForListParamDto.getServerTypeList().split(","));
                serverTypeList.removeAll(new ArrayList<>(null));
                if (serverTypeList!=null && serverTypeList.size()>0){
                    csApplyInfoParmPo.setServerTypeList(serverTypeList);
                }

            }
            csApplyInfoParmPo.setSettleStartDateEnd(csApplyInfoForListParamDto.getSettleStartDateEnd());
            csApplyInfoParmPo.setSettleStartDateStart(csApplyInfoForListParamDto.getSettleStartDateStart());
            csApplyInfoParmPo.setApprovalUserNo(csApplyInfoForListParamDto.getApprovalUserNo());
            csApplyInfoParmPo.setSettleInviteNo(csApplyInfoForListParamDto.getSettleInviteNo());
            csApplyInfoParmPo.setCarrrierSettleName(csApplyInfoForListParamDto.getCarrrierSettleName());
            csApplyInfoParmPo.setApprovalUsersInviteNo(csApplyInfoForListParamDto.getApprovalUsersInviteNo());
            csApplyInfoParmPo.setApprovalStatus(csApplyInfoForListParamDto.getApprovalStatus());
            PageInfo<CsApplyInfoForListPo> pageInfo = csApplyinfoService.queryApplyListForApproval(csApplyInfoParmPo, csApplyInfoForListParamDto.getPageNum(), csApplyInfoForListParamDto.getPageSize());
            List<CsApplyInfoForListDto> data=new ArrayList<>();
            if (pageInfo!=null && pageInfo.getList()!=null && pageInfo.getList().size()>0){
                //判断是否可以审批
                List<String> invviteNo=new ArrayList<>();
                for (CsApplyInfoForListPo csApplyInfoForListPo:pageInfo.getList()){
                    CsApplyInfoForListDto csApplyInfoForListDto=BeanJsonUtil.beanConvert(csApplyInfoForListPo,CsApplyInfoForListDto.class);
                    //渲染业务类型
                    List<String> csServerCodes=csApplyInfoForListPo.getServerType()==null?null:Arrays.asList(csApplyInfoForListPo.getServerType().split(","));
                    if (csServerCodes!=null && csServerCodes.size()>0){
                        List<String> serverNameList=new ArrayList<>();
                        for (String csServerCode:csServerCodes){
                            serverNameList.add(BusinessEnum.queryNameByItemCodeAndType(csServerCode,"cs_server_type"));
                        }
                        csApplyInfoForListDto.setServerTypeList(serverNameList);
                    }


                    //判断记录行是否可以进行审批操作，即是财务又是运营，则需要判断是否有运营审批权
                    csApplyInfoForListDto.setCanBeApproval(true);
                    if (StringUtils.equals(approvalAuthority, BusinessEnum.CARRIER_SETTLE_APPROVAL_USER_TYPE_FINANCI.getItemCode())){
                        if (StringUtils.equals(csApplyInfoForListPo.getApprovalStatus(),BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_OP.getItemCode())||
                                StringUtils.equals(csApplyInfoForListPo.getApprovalStatus(),BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_FFA.getItemCode())){
                           if (StringUtils.equals(csApplyInfoForListPo.getApprovalType(),BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_DEFAULT.getItemCode())){
                               AmAuditSettingPo amAuditSettingPo=new AmAuditSettingPo();
                               amAuditSettingPo.setStatus((byte)1);
                               amAuditSettingPo.setAuditUser(csApplyInfoForListParamDto.getApprovalUserNo());
                               amAuditSettingPo.setDefaultType(2);
                               List<AmAuditSettingPo> amAuditSettingPos2 = auditSettingService.selectSelective(amAuditSettingPo);
                               if (amAuditSettingPos2==null||amAuditSettingPos2.size()<=0){
                                   csApplyInfoForListDto.setCanBeApproval(false);
                               }
                           }else if (StringUtils.equals(csApplyInfoForListPo.getApprovalType(),BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_TRANSFER.getItemCode())){
                               if (!StringUtils.equals(csApplyInfoForListPo.getLastestTransferUserNo(),csApplyInfoForListParamDto.getApprovalUserNo())){
                                   csApplyInfoForListDto.setCanBeApproval(false);
                               }
                           }else if (StringUtils.equals(csApplyInfoForListPo.getApprovalType(),BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_SPECIAL.getItemCode()))
                               if (!StringUtils.equals(csApplyInfoForListPo.getSettleInviteNo(),csApplyInfoForListParamDto.getApprovalUsersInviteNo())){
                                   csApplyInfoForListDto.setCanBeApproval(false);
                               }
                        }


                    }
                    invviteNo.add(csApplyInfoForListDto.getSettleInviteNo());
                    data.add(csApplyInfoForListDto);
                }
                //渲染邀请人数据
                Map<String,AccountInfo> map=new HashMap<>();
                ResultData<List<AccountInfo>> accountListByInviteCodes = masterDataFeignClient.getAccountListByInviteCodes(invviteNo);
                if (accountListByInviteCodes==null ||!StringUtils.equals(ErrorCode.SUCCESS,accountListByInviteCodes.getCode())){
                    LOGGER.error("调用主数据接口，通过邀请码查询用户信息失败.result：{}",BeanJsonUtil.obj2String(accountListByInviteCodes));
                }else {
                    if (accountListByInviteCodes.getData()!=null &&accountListByInviteCodes.getData().size()>0){
                        for (AccountInfo accountInfo:accountListByInviteCodes.getData()){
                            if (accountInfo!=null){
                                map.put(accountInfo.getInvitationCode(),accountInfo);
                            }
                        }
                    }
                    for (CsApplyInfoForListDto csApplyInfoForListDto:data){
                        AccountInfo accountInfo = map.get(csApplyInfoForListDto.getSettleInviteNo());
                        if (accountInfo==null){
                            continue;
                        }
                        csApplyInfoForListDto.setInviter(accountInfo.getName()+"/"+accountInfo.getAccountNo()+"/"+accountInfo.getInvitationCode());
                    }
                }

            }
            PageResultDto<CsApplyInfoForListDto> pageInfoResult=new PageResultDto<>();
            pageInfoResult.setData(data);
            pageInfoResult.setPageCount(pageInfo.getPages());
            pageInfoResult.setTotal(pageInfo.getTotal());
            pageInfoResult.setPageSize(pageInfo.getPageSize());
            pageInfoResult.setPageNum(pageInfo.getPageNum());
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,pageInfoResult);
        } catch (Exception e) {
            LOGGER.error("查询待审批列表失败:{}",ExceptionUtils.getFullStackTrace(e));
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,new PageResultDto<>());
        }

    }

    @Override
    public ResultData<List<String>> querySettleName(String settleName) {
        ResultData<List<String>> resultData = new ResultData<>();
        try {
            List<String> result = csApplyinfoService.querySettleName(settleName);
            resultData.setData(result);
            return resultData;
        } catch (Exception e) {
            LOGGER.error("模糊查询服务商名称失败--error:{}", ExceptionUtils.getFullStackTrace(e));

            resultData.setCode(ErrorCode.QUERY_FAILOR);
            resultData.setMessage(ErrorCode.QUERY_FAILOR_MSG);
            return resultData;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData<Void> transferApplyUser(Integer applyInfoId, String operationUserNo,String destinationNo) {
        ResultData<Void> resultData = new ResultData<>();
        // 转移逻辑
        try {
            // 转移之前的申请表信息
            CsApplyInfoPo csApplyInfoPo = csApplyinfoService.queryById(applyInfoId);
            AccountInfo destinationAccoutInfo = this.queryAccountInfoByAccountNoOrInviteNo(destinationNo, null);
            AccountInfo operateAccoutInfo = this.queryAccountInfoByAccountNoOrInviteNo(operationUserNo, null);
            if (null==destinationAccoutInfo){
                return new ResultData<>(ErrorCode.FAILOR,"转移人无审批权限，请重新选择");
            }
            //校验转移人是否有审核权限
            Boolean userHasAuditPrivilege = auditSettingService.isUserHasAuditPrivilege(destinationNo);

            if (!userHasAuditPrivilege){
                //校验是否是默认审核人
                AmAuditSettingPo amAuditSettingPo=new AmAuditSettingPo();
                amAuditSettingPo.setStatus((byte)1);
                amAuditSettingPo.setDefaultType(2);
                amAuditSettingPo.setAuditUser(destinationNo);
                List<AmAuditSettingPo> amAuditSettingPos = auditSettingService.selectSelective(amAuditSettingPo);
                if (amAuditSettingPos==null || amAuditSettingPos.size()<=0){
                    return new ResultData<>(ErrorCode.FAILOR,"转移人无审批权限，请重新选择");
                }
            }
            //修改申请单相关属性
            csApplyInfoPo.setApprovalType(BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_TRANSFER.getItemCode());
            csApplyInfoPo.setLastestTransferUserNo(destinationNo);
            csApplyInfoPo.setModifyDate(new Date());
            csApplyinfoService.update(csApplyInfoPo);
            //插入审批记录
            ApprovalRecordPo approvalRecordPo=new ApprovalRecordPo();
            approvalRecordPo.setApprovalApplyId(applyInfoId);
            approvalRecordPo.setApprovalType(BusinessEnum.APPROVAL_TYPE_CS_OPERATION.getItemCode());
            approvalRecordPo.setApprovalTime(new Date());
            approvalRecordPo.setApprovalUserNo(operationUserNo);
            approvalRecordPo.setApprovaUserName(operateAccoutInfo.getName());
            approvalRecordPo.setApprovalResultContent(operateAccoutInfo.getName()+"("+operateAccoutInfo.getAccountNo()+")将审核权转移给"+destinationAccoutInfo.getName()+"("+destinationAccoutInfo.getAccountNo()+")");
            approvalRecordPo.setApprovalResult(BusinessEnum.APPROVAL_STATUS_CHANGE.getItemCode());
            approvalRecordService.insert(approvalRecordPo);
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        } catch (Exception e) {
            LOGGER.error("审核人转移失败--error:{}", ExceptionUtils.getFullStackTrace(e));
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultData.setCode(ErrorCode.FAILOR);
            resultData.setMessage(ErrorCode.FAILOR_MSG);
            return resultData;
        }
    }


    @Override
    public ResultData<CsApplyInfoDto> queryApplyDraft(String csPhone) {
        try {
            CsApplyInfoPo csApplyInfoPo=new CsApplyInfoPo();
            csApplyInfoPo.setCsPhone(csPhone);
            csApplyInfoPo.setApprovalStatus(BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS__DRA.getItemCode());
            PageInfo<CsApplyInfoPo> csApplyInfoPoPageInfo = csApplyinfoService.queryApplyInfoBySelective(csApplyInfoPo, 1, 1);
            if (csApplyInfoPoPageInfo!=null && csApplyInfoPoPageInfo.getList()!=null && csApplyInfoPoPageInfo.getList().size()>0){
                Integer applyId=csApplyInfoPoPageInfo.getList().get(0).getId();
                return this.getApprovalDetailById(applyId);
            }
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        } catch (Exception e) {
            LOGGER.error("查询草稿出现异常:{}",ExceptionUtils.getFullStackTrace(e));
            return new ResultData<>(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }
    }

    @Override
    public ResultData<PageResultDto<CsApplyInfoDto>> queryApplyListByCsphone(String csPhone,Integer pageNum,Integer pageSize) {
        try {
            CsApplyInfoPo csApplyInfoPo=new CsApplyInfoPo();
            csApplyInfoPo.setCsPhone(csPhone);
            PageInfo<CsApplyInfoPo> pageInfo = csApplyinfoService.queryApplyInfoBySelective(csApplyInfoPo, pageNum, pageSize);
            PageResultDto<CsApplyInfoDto> pageResultDto=new PageResultDto<>();
            List<CsApplyInfoDto> data=new ArrayList<>();
            if (pageInfo!=null && pageInfo.getList()!=null && pageInfo.getList().size()>0){
                for (CsApplyInfoPo csApplyInfoPo1:pageInfo.getList()){
                    //渲染审批状态值
                    CsApplyInfoDto csApplyInfoDto=BeanJsonUtil.beanConvert(csApplyInfoPo1,CsApplyInfoDto.class);
                    csApplyInfoDto.setApprovalStatusDesc(BusinessEnum.queryNameByItemCodeAndType(csApplyInfoDto.getApprovalStatus(),"cs_approval_status"));
                   /* if (StringUtils.equals(csApplyInfoDto.getApprovalStatus(),BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_FFQ.getItemCode())
                            ||StringUtils.equals(csApplyInfoDto.getApprovalStatus(),BusinessEnum.CARRIER_SETTLE_APPROVAL_STATUS_OF.getItemCode())){
                        csApplyInfoDto.setApprovalStatus("0");
                        csApplyInfoDto.setApprovalStatusDesc("审核不通过");
                    }*/
                    //渲染业务类型中文
                    if (csApplyInfoDto.getServerType()!=null){
                        List<String> serverTypeCodeList=Arrays.asList(csApplyInfoDto.getServerType().split(","));
                        StringBuffer serverNName=new StringBuffer();
                        for (String code:serverTypeCodeList){
                            serverNName.append(BusinessEnum.queryNameByItemCodeAndType(code,"cs_server_type")).append(",");
                        }
                        csApplyInfoDto.setServerType(serverNName.substring(0,serverNName.length()-1));
                    }
                    data.add(csApplyInfoDto);
                }
            }
            pageResultDto.setData(data);
            pageResultDto.setPageNum(pageInfo.getPageNum());
            pageResultDto.setPageSize(pageInfo.getPageSize());
            pageResultDto.setTotal(pageInfo.getTotal());
            pageResultDto.setPageCount(pageInfo.getPages());
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,pageResultDto);
        } catch (Exception e) {
            LOGGER.error("通过服务商手机号查询申请列表失败{}",ExceptionUtils.getFullStackTrace(e));
            return new ResultData<>(ErrorCode.QUERY_FAILOR,ErrorCode.QUERY_FAILOR_MSG,new PageResultDto<>());
        }
    }

    /**
     * 检查用户审批完整身份(判断权限交叉，用于前端控制按钮)
     * @param userNo 1：财务  2 运营  3 财务+运营
     * @return
     */
    @Override
    public ResultData<String> getUsersApprovallevel(String userNo) {
        try {
            StringBuffer levelStr=new StringBuffer();
            AmAuditSettingPo amAuditSettingPo=new AmAuditSettingPo();
            amAuditSettingPo.setStatus((byte)1);
            amAuditSettingPo.setAuditUser(userNo);
            amAuditSettingPo.setDefaultType(1);
            List<AmAuditSettingPo> amAuditSettingPos = auditSettingService.selectSelective(amAuditSettingPo);
            if (amAuditSettingPos!=null && amAuditSettingPos.size()>0){
                //1:校验是否是财务审核人
                levelStr.append("1");
            }
            AmAuditSettingPo amAuditSettingPo2=new AmAuditSettingPo();
            amAuditSettingPo2.setStatus((byte)1);
            amAuditSettingPo2.setAuditUser(userNo);
            amAuditSettingPo2.setDefaultType(2);
            List<AmAuditSettingPo> amAuditSettingPos2 = auditSettingService.selectSelective(amAuditSettingPo2);
            if (amAuditSettingPos2!=null && amAuditSettingPos2.size()>0){
                //1:校验是否是默认运营审核人
                levelStr.append("2");
            }
            //3:校验是否是一般审核权限
            Boolean isUserHasAuditPrivilege= auditSettingService.isUserHasAuditPrivilege(userNo);
            if (isUserHasAuditPrivilege){
                levelStr.append("3");
            }
            ResultData<String> resultData=new ResultData<>();
            resultData.setCode(ErrorCode.SUCCESS);
            resultData.setMessage(ErrorCode.SUCCESS_MSG);
            switch (levelStr.toString()){
                case "1" :
                    resultData.setData("1");
                    break;
                case "2":
                    resultData.setData("2");
                    break;
                case "3":
                    resultData.setData("2");
                    break;
                case "12":
                    resultData.setData("3");
                    break;
                case "123":
                    resultData.setData("3");
                    break;
                case "13":
                    resultData.setData("3");
                    break;
                case "23":
                    resultData.setData("2");
                    break;
            }
            return resultData;
        } catch (Exception e) {
            LOGGER.error("检查用户审批完整身份失败{}",ExceptionUtils.getFullStackTrace(e));
            return new ResultData<>(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG,null);
        }
    }

    /**
     * 检查用户审批最大身份(只返回最大审批权限。没判断权限交叉，用于筛选审批列表)
     * @param userNo
     * @return
     */
    public String checkApprovalAuthority(String userNo){
        ResultData<String> resultData=new ResultData<>();
        resultData.setCode(ErrorCode.SUCCESS);
        resultData.setMessage(ErrorCode.SUCCESS_MSG);
        if (StringUtils.isBlank(userNo)){
            return null;
        }
        AmAuditSettingPo amAuditSettingPo=new AmAuditSettingPo();
        amAuditSettingPo.setStatus((byte)1);
        amAuditSettingPo.setAuditUser(userNo);
        amAuditSettingPo.setDefaultType(1);
        List<AmAuditSettingPo> amAuditSettingPos = auditSettingService.selectSelective(amAuditSettingPo);
        if (amAuditSettingPos!=null || amAuditSettingPos.size()>0){
            //1:校验是否是财务审核人
            return  BusinessEnum.CARRIER_SETTLE_APPROVAL_USER_TYPE_FINANCI.getItemCode();

        }
        AmAuditSettingPo amAuditSettingPo2=new AmAuditSettingPo();
        amAuditSettingPo2.setStatus((byte)1);
        amAuditSettingPo2.setAuditUser(userNo);
        amAuditSettingPo2.setDefaultType(2);
        List<AmAuditSettingPo> amAuditSettingPos2 = auditSettingService.selectSelective(amAuditSettingPo2);
        if (amAuditSettingPos2!=null || amAuditSettingPos2.size()>0){
            //1:校验是否是默认运营审核人
         return BusinessEnum.CARRIER_SETTLE_APPROVAL_USER_TYPE_BUSINESS.getItemCode();
        }
        //3:校验是否是一般审核权限
        Boolean isUserHasAuditPrivilege= auditSettingService.isUserHasAuditPrivilege(userNo);
        if (isUserHasAuditPrivilege){
          return BusinessEnum.CARRIER_SETTLE_APPROVAL_USER_TYPE_FORMAL.getItemCode();
        }
        return null;
    }

    /**
     * 根据用户账号或者邀请码获取用户数据
     * @param accountNo
     * @param inviteNo
     * @return
     */
    public AccountInfo queryAccountInfoByAccountNoOrInviteNo(String accountNo,String inviteNo){
        if (StringUtils.isBlank(accountNo)){
            //通过邀请码获取用户信息
            List<String> settleInviteNoList=new ArrayList<>();
            settleInviteNoList.add(inviteNo);
            LOGGER.info("调用主数据接口,通过邀请码获取用户信息，param:{}",inviteNo);
            ResultData<List<AccountInfo>> accountListByInviteCodes = masterDataFeignClient.getAccountListByInviteCodes(settleInviteNoList);
            LOGGER.info("调用主数据接口,通过邀请码获取用户信息，result:{}",BeanJsonUtil.obj2String(accountListByInviteCodes));
            if (accountListByInviteCodes==null ||!StringUtils.equals(accountListByInviteCodes.getCode(),ErrorCode.SUCCESS)){
                return null;
            }
            if (accountListByInviteCodes.getData()!=null&&accountListByInviteCodes.getData().size()>0){
                return accountListByInviteCodes.getData().get(0);
            }
        }else {
            //通过账号获取用户信息
            LOGGER.info("调用主数据接口,通过用户账号获取用户信息，param:{}",accountNo);
            ResultData<AccountInfo> userByAccountNo = masterDataFeignClient.getUserByAccountNo(accountNo);
            LOGGER.info("调用主数据接口,通过用户账号获取用户信息，result:{}",BeanJsonUtil.obj2String(userByAccountNo));
            if (userByAccountNo==null ||!StringUtils.equals(userByAccountNo.getCode(),ErrorCode.SUCCESS)){
                return null;
            }
            if (userByAccountNo.getData()!=null){
                return userByAccountNo.getData();
            }
        }
        return null;
    }

    @Override
    public List<CsApplyInfoPo> queryByIds(List<Integer> ids) {
        return csApplyinfoService.queryByIds(ids);
    }


    @Override
    public ResultData<Void> remindBusinessApproval() {
        try {
            List<CsApplyInfoPo> csApplyInfoPos = csApplyinfoService.queryApplyInfoForApprovalRemind();
            if (csApplyInfoPos!=null && csApplyInfoPos.size()>0){
                Map<String,String> userNameMap=new HashMap<>();
                //0：获取默认运营审核人
                String defaultPhone=null;
                AmAuditSettingPo amAuditSettingPo=new AmAuditSettingPo();
                amAuditSettingPo.setStatus((byte)1);
                amAuditSettingPo.setDefaultType(2);
                List<AmAuditSettingPo> amAuditSettingPos = auditSettingService.selectSelective(amAuditSettingPo);
                if (amAuditSettingPos!=null && amAuditSettingPos.size()>0){
                    ResultData<AccountInfo> accountInfoResultData = masterDataFeignClient.getUserByAccountNo(amAuditSettingPos.get(0).getUserCode());
                    if (accountInfoResultData.getData()!=null){
                        defaultPhone=accountInfoResultData.getData().getPhone();
                        userNameMap.put(defaultPhone,accountInfoResultData.getData().getName());
                    }
                }
                //每个人待处理的单数
                Map<String,Integer> phoneMap=new HashMap<>();
                Map<String,Integer> inviteMap=new HashMap<>();
                Map<String,Integer> accountNoMap=new HashMap<>();
                for (CsApplyInfoPo csApplyInfoPo:csApplyInfoPos){
                    //1：校验单子类型
                    //2:根据单子类型获取审批人
                   String approvalType= csApplyInfoPo.getApprovalType();
                   if (StringUtils.equals(approvalType,BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_DEFAULT.getItemCode())){
                        //默认运营审批
                       phoneMap.put(defaultPhone,phoneMap.get(defaultPhone)==null?1:phoneMap.get(defaultPhone)+1);
                   } else if (StringUtils.equals(approvalType,BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_SPECIAL.getItemCode())) {
                       //邀请人审批，汇总邀请码和单数，避免多次调用主数据接口
                       inviteMap.put(csApplyInfoPo.getSettleInviteNo(),inviteMap.get(csApplyInfoPo.getLastestTransferUserNo())==null?1:inviteMap.get(csApplyInfoPo.getLastestTransferUserNo())+1);
                   }else if (StringUtils.equals(approvalType,BusinessEnum.CARRIER_SETTLE_APPROVAL_TYPE_TRANSFER.getItemCode()))
                        //转移单，转移人审核,汇总转移人编码和单数，避免多次调用主数据接口
                       accountNoMap.put(csApplyInfoPo.getLastestTransferUserNo(),accountNoMap.get(csApplyInfoPo.getLastestTransferUserNo())==null?1:accountNoMap.get(csApplyInfoPo.getLastestTransferUserNo())+1);
                }
                //将inviteMap 、accountNoMap 转换成PhoneMap
               if (inviteMap!=null && inviteMap.keySet().size()>0){
                   Set<String> keySet = inviteMap.keySet();
                   List<String> inviteNos=new ArrayList<>(keySet);
                   ResultData<List<AccountInfo>> accountListByInviteCodes = masterDataFeignClient.getAccountListByInviteCodes(inviteNos);
                   if (accountListByInviteCodes!=null &&accountListByInviteCodes.getData()!=null &&accountListByInviteCodes.getData().size()>0){
                       for (AccountInfo accountInfo:accountListByInviteCodes.getData()){
                           phoneMap.put(accountInfo.getPhone(),phoneMap.get(accountInfo.getPhone())==null?1:phoneMap.get(accountInfo.getPhone())+1);
                           userNameMap.put(accountInfo.getPhone(),accountInfo.getName());
                       }
                   }
               }
               if (accountNoMap!=null && accountNoMap.keySet().size()>0){
                   Set<String> keySet = accountNoMap.keySet();
                   List<String> accountNos=new ArrayList<>(keySet);
                   for (String accountNo:accountNos){
                       ResultData<AccountInfo> userByAccountNo = masterDataFeignClient.getUserByAccountNo(accountNo);
                       if (userByAccountNo!=null &&userByAccountNo.getData()!=null){
                           phoneMap.put(userByAccountNo.getData().getPhone(),phoneMap.get(userByAccountNo.getData().getPhone())==null?1:phoneMap.get(userByAccountNo.getData().getPhone())+1);
                           userNameMap.put(userByAccountNo.getData().getPhone(),userByAccountNo.getData().getName());
                       }
                   }
               }
                //发送短信
                if (phoneMap!=null && phoneMap.keySet().size()>0){
                    for (String phone:phoneMap.keySet()){
                        ResultData resultData = smsSendFacade.sendSmsWithAxwlConfig(phone, messageForBusiness.replace("username", userNameMap.get(phone)).replace("num", phoneMap.get(phone) + ""));
                    }
                }
            }
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        } catch (Exception e) {
            LOGGER.error("定时提醒运营进行审批，出现异常{}",ExceptionUtils.getFullStackTrace(e));
            return new ResultData<>(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }
    }

    @Override
    public ResultData<List<Account>> findInviter(String parm) {
        return masterDataFeignClient.queryInviteCode(parm);
    }

    /**
     * 财务审核完的送签
     * @return
     */
    public String sendSignInBusnies(CsApplyInfoPo csApplyInfoPo,String contractName,AccountInfo accountInfo){
        try {
            BuildEmptyContractRequest buildEmptyContractRequest=new BuildEmptyContractRequest();
            buildEmptyContractRequest.setApplyInfoId(csApplyInfoPo.getId());
            buildEmptyContractRequest.setTemplateNo(csApplyInfoPo.getCmContractTemplateNo());
            buildEmptyContractRequest.setContractName(contractName);
            buildEmptyContractRequest.setCarrierPhone(csApplyInfoPo.getCsPhone());
            buildEmptyContractRequest.setCarrierName(csApplyInfoPo.getCarrrierSettleName());
            buildEmptyContractRequest.setCompanyName(companyName);
            buildEmptyContractRequest.setAuditName(accountInfo.getName());
            buildEmptyContractRequest.setCompanyName(companyName);
            buildEmptyContractRequest.setCarrierCode(csApplyInfoPo.getCsPhone());
            buildEmptyContractRequest.setAuditCode(accountInfo.getAccountNo());
            if (csApplyInfoPo.getIsHavingLicense().intValue()==0){
                //个体用户
                CsBasicInfoPo csBasicInfoPo=csBasicInfoService.queryById(csApplyInfoPo.getCsBasicInfoId());
                buildEmptyContractRequest.setStatus(1);
                buildEmptyContractRequest.setIdentity(csBasicInfoPo.getCorporationIdCard());
            }else {
                CsLicenseInfoPo csLicenseInfoPo = csLicenseInfoService.queryById(csApplyInfoPo.getCsLicenseInfoId());
                buildEmptyContractRequest.setStatus(2);
                buildEmptyContractRequest.setCorporationName(csLicenseInfoPo.getCorparationName());
                buildEmptyContractRequest.setCertificate(csLicenseInfoPo.getLicenseCode());
                buildEmptyContractRequest.setAddress(csLicenseInfoPo.getLicenseAddress());
            }
            LOGGER.info("运营审核完，调用送签buildEmptyContract()。param：{}",BeanJsonUtil.obj2String(buildEmptyContractRequest));
            String contractNo = contractFacade.buildEmptyContract(buildEmptyContractRequest);
            //关联上合同
            return contractNo;
        } catch (ZQException e) {
            LOGGER.error("运营审核完，调用送签buildEmptyContract()。error:{}",ExceptionUtils.getFullStackTrace(e));
            throw new RuntimeException("送签失败");
        }
    }

    /**
     * 财务确认完的签署
     * @return
     */
    public Boolean sendSignInFinance(Integer applyInfoId,Integer auditStatus,String signName,String unpassReason){
        try {
            LOGGER.info("财务签署完，确认送签signByAoc():applyInfoId={},auditStatus={},signName={},unpassReaSon={}",applyInfoId,auditStatus,signName,unpassReason);
            contractFacade.signByAoc(applyInfoId,auditStatus,signName,unpassReason);
        } catch (ZQException e) {
            LOGGER.error("财务签署完，确认送签signByAoc()。error:{}",ExceptionUtils.getFullStackTrace(e));
            throw new RuntimeException("签署失败");
        }
        return true;
    }
}
